﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartChess
{
    class Match
    {
        protected Brain[] _players;  
        public Game _game;
        private Brain _currentPlayer;

        public Match(Brain player1, Brain player2)
        {
            _players = new Brain[2];
            _players[0] = player1;
            _players[1] = player2;

            _game = new Game();
            _currentPlayer = player2;
        }
        public Brain Player1
        { 
            get { return _players[0]; } 
        }
        public Brain Player2
        { 
            get { return _players[1]; } 
        }
        public Brain CurrentPlayer
        {
            get { return _currentPlayer; }
        }
        public Game Game
        {
            get { return _game; }
        }
        //Diese Methode wird für jeden Zug aufgerufen.
        //Es wird jeweils die SelectMoveAsync Methode des jeweiligen Brains aufgerufen.
        public async void NextMove()
        {
            ChessMove move = await _currentPlayer.SelectMoveAsync(_game, GetPlayerId(_currentPlayer));
            MakeMove(move);
            _currentPlayer = Opponent(_currentPlayer);
        }
        public void MakeMove(ChessMove move)
        {
            OnMoved(move);
            _game.MakeMove(move);
        }
        public Brain Opponent(Brain player)
        {
            return _players[1 - GetPlayerId(player)];
        }
        public int GetPlayerId(Brain player)
        {
            if (player == _players[0])
                return 0;
            else if (player == _players[1])
                return 1;
            else
                throw new ArgumentException("Can't get Id of unknown player.");
        }
        // Ein Ereignis, das feuert, wenn ein Zug ausgeführt wurde.
        public event GameEventHandler Moved;

        public delegate void GameEventHandler(object sender, GameEventArgs e);

        protected void OnMoved(ChessMove move)
        {
            if (Moved != null)
            {
                Moved(this, new GameEventArgs(move));
            }
        }

    }
    public class GameEventArgs : EventArgs
    {
        public ChessMove Move { get; private set; }
        public GameEventArgs(ChessMove move)
        {
            Move = move;
        }
    }
}

